package com.renjian.spring.day05.dao;

import com.renjian.spring.day05.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(User user) {
        String sql="insert into t_book values(?,?,?)";
        int update = jdbcTemplate.update(sql, user.getUser_id(), user.getUsername(), user.getUser_status());
        System.out.println("插入数据："+update);
    }

    @Override
    public void update(User user) {
        String sql = "update t_book set username=?,user_status=? where user_id=?";
        int update = jdbcTemplate.update(sql, user.getUsername(), user.getUser_status(), user.getUser_id());
        System.out.println("修改数据："+update);
    }

    @Override
    public void delete(String id) {
        String sql = "delete from t_book where user_id=?";
        int update = jdbcTemplate.update(sql,id);
        System.out.println("按id删除："+update);
    }

    @Override
    public void onlyOne() {
        String sql = "select count(*) from t_book";
        Integer integer = jdbcTemplate.queryForObject(sql, int.class);
        System.out.println("求表中总记录数："+integer);
    }

    @Override
    public void reObj(String id) {
        String sql = "select * from t_book where user_id = ?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        System.out.println("查询返回一个对象："+user);
    }

    @Override
    public void reObjs() {
        String sql = "select *from t_book";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        System.out.println("返回一个集合："+users);
    }

    @Override
    public void batchAdd(List<Object[]> list) {
        String sql="insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, list);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchUpdate(List<Object[]> list) {
        String sql = "update t_book set username=?,user_status=? where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, list);
        System.out.println(Arrays.toString(ints));

    }

    @Override
    public void batchDelete(List<Object[]> list) {
        String sql = "delete from t_book where user_id=?";
        jdbcTemplate.batchUpdate(sql,list);
    }
}
